package SystemC;

/******************************************************************************************************************
* File:SMConsole.java
* Course: 17655
* Project: Assignment 3
* Copyright: Copyright (c) 2013 Carnegie Mellon University
* Versions:
*	1.0 March 2013 - luisrocha
*
* Description: This class is the service management console for the museum environmental control system. 
* The SMConsole displays all registered equipments with the system. It also detects when a device is no
* no longer responding and notifies user via the console
*
******************************************************************************************************************/
import EventPackage.*;
import TermioPackage.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

public class SMConsole
{
    static Map<String,String> deviceTypes = null;        // to hold the list of valid device types

    public static void InitializeDeviceTypes()
    {
        //creates the list of known device types and respective short descriptions
        deviceTypes = new HashMap();
        deviceTypes.put("HCT", "Humidity Controller");
        deviceTypes.put("HCTD", "Controls the humidity by turning humidifier and deshumidifier on/off");
        deviceTypes.put("HSN", "Humidity Sensor");
        deviceTypes.put("HSND", "Reads the humidity values");
        deviceTypes.put("TCT", "Temperature Controller");
        deviceTypes.put("TCTD", "Controlls the temperature by turning the heater and chiller on/off");
        deviceTypes.put("TSN", "Temperature Sensor");
        deviceTypes.put("TSND", "Reads the temperature values");
        deviceTypes.put("MCS", "ECS Monitoring Console");
        deviceTypes.put("CSLD", "Allows to set the temperature and humidity thresholds");
        deviceTypes.put("SMC", "Service Management Console");
        deviceTypes.put("SMCD", "Allows to list active components and monitor status");       
    }  // initializeDeviceTypes


    public static void main(String args[])
    {
        Termio UserInput = new Termio();                // Termio IO Object
        boolean Done = false;				// Main loop flag
        String Option = null;				// Menu choice from user
        Event Evt = null;				// Event object
        boolean Error = false;				// Error flag
        SMMonitor Monitor = null;			// The environmental control system monitor

        //build the map with all known device types and descriptions
        InitializeDeviceTypes(); 

        /////////////////////////////////////////////////////////////////////////////////
        // Get the IP address of the event manager
        /////////////////////////////////////////////////////////////////////////////////

        if ( args.length != 0 )
        {
                // event manager is not on the local system

                Monitor = new SMMonitor( args[0] );

        } else {

                Monitor = new SMMonitor();

        } // if


        // Here we check to see if registration worked. If ef is null then the
        // event manager interface was not properly created.

        if (Monitor.IsRegistered() )
        {
            Monitor.start(); // Here we start the monitoring and control thread

            while (!Done)
            {
                // Here, the main thread continues and provides the main menu

                System.out.println( "\n\n" );
                System.out.println( "Environmental Control System (ECS) Service Management Console" );

                if (args.length != 0)
                        System.out.println( "Using event manager at: " + args[0] );
                else
                        System.out.println( "Using local event manger" );

                System.out.println( "Select an Option: " );
                System.out.println( "1: List Current Registered Equipment" );
                System.out.println( "2: List Last Heartbeat of Registered Equipment" );
                System.out.println( "3: List Unresponsive Equipment" );
                System.out.println( "X: Stop System\n" );
                System.out.print( "\n>>>> " );
                Option = UserInput.KeyboardReadString();

                //////////// option 1 ////////////

                if ( Option.equals( "1" ) )
                {
                    // Here we display the list of equipment in the system
                    System.out.print( "\nList of Equipment registered in the system: " );                           
                    for (Device i : Monitor.getDeviceList().values())
                    {
                        String typeNameAndDesc = null;
                        //if the device has a type that we know, get the name and description
                        if ( deviceTypes.containsKey(i.getDeviceType()) )
                        {
                           typeNameAndDesc = i.getDeviceType() + 
                                " - " + deviceTypes.get(i.getDeviceType()) +
                                " - " + deviceTypes.get(i.getDeviceType()+"D");
                        }
                        //otherwise note that the device is unknown
                        else
                        {
                            typeNameAndDesc = "UNKNOWN Device Type";
                        }
                        System.out.print( "\n Device: " + i.getDeviceID() + 
                                " Type: " + typeNameAndDesc);
                    }
                } //if

                //////////// option 2 ////////////
                if ( Option.equals( "2" ) )
                {
                    // Here we display the list of equipment in the system
                    System.out.print( "\nList of last heartbeat for equipment registered in the system: " );                           
                    for (Device i : Monitor.getDeviceList().values())
                    {                                     
                        Calendar TimeStamp = Calendar.getInstance();
                        TimeStamp.setTimeInMillis(i.getDeviceLastHeartbeat());
                        SimpleDateFormat TimeStampFormat = new SimpleDateFormat("yyyy MM dd::hh:mm:ss:SSS");
                        String TimeString = TimeStampFormat.format(TimeStamp.getTime());

                        System.out.print( "\n Device: " + i.getDeviceType() +
                                " " + i.getDeviceID() + 
                                " Last Heartbeat: " + TimeString);
                    }

                } // if

                //////////// option 3 ////////////
                if ( Option.equals( "3" ) )
                {
                    // Here we display the list of equipment in the system
                    System.out.print( "\nList of unresponsive equipment registered in the system: " );                           
                    Map<Long,Device> unresponsiveDeviceList = new HashMap();

                    unresponsiveDeviceList = Monitor.getUnresponsiveDeviceList();

                    if ( unresponsiveDeviceList == null || unresponsiveDeviceList.isEmpty() )
                    {
                       System.out.print( "\n ---- All Devices are responsive ----");                                     
                    } // if
                    else
                    {
                        for (Device i : unresponsiveDeviceList.values())
                        {                                     
                            Calendar TimeStamp = Calendar.getInstance();
                            TimeStamp.setTimeInMillis(i.getDeviceLastHeartbeat());
                            SimpleDateFormat TimeStampFormat = new SimpleDateFormat("yyyy MM dd::hh:mm:ss:SSS");
                            String TimeString = TimeStampFormat.format(TimeStamp.getTime());

                            System.out.print( "\n Device: " + i.getDeviceType() +
                                " " + i.getDeviceID() + 
                                " Last Heartbeat: " + TimeString);
                        }  //for                                        
                    } // else

                } // if

                //////////// option X ////////////

                if ( Option.equalsIgnoreCase( "X" ) )
                {
                        // Here the user is done, so we set the Done flag and halt
                        // the environmental control system. The monitor provides a method
                        // to do this. Its important to have processes release their queues
                        // with the event manager. If these queues are not released these
                        // become dead queues and they collect events and will eventually
                        // cause problems for the event manager.

                        Monitor.Halt();
                        Done = true;
                        System.out.println( "\nConsole Stopped... Exit monitor window to return to command prompt." );
                        Monitor.Halt();

                } // if

            } // while

        } else {

                System.out.println("\n\nUnable start the monitor.\n\n" );

        } // if

    } // main

} // ECSConsole
